"""
日志配置和管理
Logging configuration and management for SchedulerAI
"""

import logging
import logging.config
import os
import sys
from datetime import datetime
from typing import Any, Dict


def setup_logging(
    log_level: str = "INFO",
    log_file: str = None,
    enable_console: bool = True,
    log_format: str = None,
) -> None:
    """
    设置日志配置
    Setup logging configuration

    Args:
        log_level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        log_file: 日志文件路径，None表示不写入文件
        enable_console: 是否启用控制台输出
        log_format: 自定义日志格式
    """

    # 默认日志格式
    if log_format is None:
        log_format = (
            "%(asctime)s - %(name)s - %(levelname)s - "
            "%(funcName)s:%(lineno)d - %(message)s"
        )

    # 创建日志配置
    config = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "standard": {"format": log_format, "datefmt": "%Y-%m-%d %H:%M:%S"},
            "detailed": {
                "format": (
                    "%(asctime)s - %(name)s - %(levelname)s - "
                    "%(pathname)s:%(lineno)d - %(funcName)s() - %(message)s"
                ),
                "datefmt": "%Y-%m-%d %H:%M:%S",
            },
        },
        "handlers": {},
        "loggers": {
            "scheduler_ai": {"level": log_level, "handlers": [], "propagate": False},
            "": {"level": "WARNING", "handlers": []},  # root logger
        },
    }

    # 添加控制台处理器
    if enable_console:
        config["handlers"]["console"] = {
            "class": "logging.StreamHandler",
            "level": log_level,
            "formatter": "standard",
            "stream": "ext://sys.stdout",
        }
        config["loggers"]["scheduler_ai"]["handlers"].append("console")

    # 添加文件处理器
    if log_file:
        # 确保日志目录存在
        log_dir = os.path.dirname(log_file)
        if log_dir and not os.path.exists(log_dir):
            os.makedirs(log_dir)

        config["handlers"]["file"] = {
            "class": "logging.handlers.RotatingFileHandler",
            "level": log_level,
            "formatter": "detailed",
            "filename": log_file,
            "maxBytes": 10 * 1024 * 1024,  # 10MB
            "backupCount": 5,
            "encoding": "utf-8",
        }
        config["loggers"]["scheduler_ai"]["handlers"].append("file")

    # 应用配置
    logging.config.dictConfig(config)


def get_logger(name: str = None) -> logging.Logger:
    """
    获取日志记录器
    Get logger instance
    """
    if name is None:
        name = "scheduler_ai"
    elif not name.startswith("scheduler_ai"):
        name = f"scheduler_ai.{name}"

    return logging.getLogger(name)


class PerformanceLogger:
    """性能日志记录器"""

    def __init__(self, operation: str, logger: logging.Logger = None):
        self.operation = operation
        self.logger = logger or get_logger("performance")
        self.start_time = None
        self.context_data = {}

    def add_context(self, key: str, value: Any):
        """添加上下文数据"""
        self.context_data[key] = value

    def __enter__(self):
        self.start_time = datetime.now()
        self.logger.info(f"开始执行: {self.operation}")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.start_time:
            duration = (datetime.now() - self.start_time).total_seconds()

            if exc_type:
                self.logger.error(
                    f"执行失败: {self.operation} (耗时: {duration:.3f}秒)",
                    extra={
                        "operation": self.operation,
                        "duration": duration,
                        "error": str(exc_val),
                        "context": self.context_data,
                    },
                )
            else:
                self.logger.info(
                    f"执行完成: {self.operation} (耗时: {duration:.3f}秒)",
                    extra={
                        "operation": self.operation,
                        "duration": duration,
                        "context": self.context_data,
                    },
                )


class APILogger:
    """API请求日志记录器"""

    def __init__(self, endpoint: str, logger: logging.Logger = None):
        self.endpoint = endpoint
        self.logger = logger or get_logger("api")
        self.start_time = None
        self.request_data = {}

    def log_request(self, **kwargs):
        """记录请求信息"""
        self.request_data.update(kwargs)
        self.start_time = datetime.now()
        self.logger.info(
            f"API请求: {self.endpoint}",
            extra={"endpoint": self.endpoint, "request_data": self.request_data},
        )

    def log_response(self, success: bool, **kwargs):
        """记录响应信息"""
        duration = None
        if self.start_time:
            duration = (datetime.now() - self.start_time).total_seconds()

        log_level = logging.INFO if success else logging.ERROR
        self.logger.log(
            log_level,
            f"API响应: {self.endpoint} ({'成功' if success else '失败'})",
            extra={
                "endpoint": self.endpoint,
                "success": success,
                "duration": duration,
                "response_data": kwargs,
            },
        )


def log_system_info():
    """记录系统信息"""
    logger = get_logger("system")

    logger.info(
        "系统信息",
        extra={
            "python_version": sys.version,
            "platform": sys.platform,
            "working_directory": os.getcwd(),
            "environment_variables": {
                key: value
                for key, value in os.environ.items()
                if key.startswith(("SCHEDULER_", "LOG_"))
            },
        },
    )


def configure_uvicorn_logging():
    """配置uvicorn日志"""
    # 禁用uvicorn的默认日志配置
    uvicorn_logger = logging.getLogger("uvicorn")
    uvicorn_access_logger = logging.getLogger("uvicorn.access")

    # 设置日志级别
    uvicorn_logger.setLevel(logging.INFO)
    uvicorn_access_logger.setLevel(logging.INFO)

    # 使用我们的格式化器
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )

    # 更新现有处理器的格式化器
    for handler in uvicorn_logger.handlers:
        handler.setFormatter(formatter)

    for handler in uvicorn_access_logger.handlers:
        handler.setFormatter(formatter)


# 默认日志配置
def init_default_logging():
    """初始化默认日志配置"""
    log_level = os.getenv("LOG_LEVEL", "INFO").upper()
    log_file = os.getenv("LOG_FILE")

    setup_logging(log_level=log_level, log_file=log_file, enable_console=True)

    # 记录启动信息
    logger = get_logger()
    logger.info("SchedulerAI日志系统已初始化")
    log_system_info()


# 在模块导入时自动初始化日志
if not logging.getLogger("scheduler_ai").handlers:
    init_default_logging()
